package com.ncd.form.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ncd.common.utils.StringUtils;
import com.ncd.form.domain.FormDict;
import com.ncd.form.domain.LayoutCell;
import com.ncd.form.domain.LayoutVersion;
import com.ncd.form.domain.RecordItm;
import com.ncd.form.mapper.LayoutCellMapper;
import com.ncd.form.mapper.LayoutVersionMapper;
import com.ncd.form.mapper.RecordItmMapper;
import com.ncd.form.service.IFormDictService;
import com.ncd.form.service.ILayoutCellService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class LayoutCellServiceIml extends ServiceImpl<LayoutCellMapper, LayoutCell> implements ILayoutCellService {

    @Resource
    LayoutVersionMapper layoutVersionMapper;

    @Resource
    RecordItmMapper recordItmMapper;

    @Resource
    IFormDictService dictService;

    @Override
    public List<LayoutCell> display(Long versionId, Long recordId) {
        List<RecordItm> recordItms=new ArrayList<>();
        Map<String,List<RecordItm>> recordItmMap=new HashMap<>();
        if(null!=recordId){
            recordItms=recordItmMapper.selectList(new LambdaQueryWrapper<RecordItm>().eq(RecordItm::getRecordId,recordId));

            for(RecordItm recordItm1:recordItms){
                String rowKey=recordItm1.getDictId()+"-"+ StringUtils.nvl(recordItm1.getRowKey(),"");
                if(recordItmMap.containsKey(rowKey)){
                    recordItmMap.get(rowKey).add(recordItm1);
                }else{
                    List<RecordItm> recordItms1=new ArrayList<>();
                    recordItms1.add(recordItm1);
                    recordItmMap.put(rowKey,recordItms1);
                }
            }
        }
        List<LayoutCell> layoutCells=this.baseMapper.selectList(new LambdaQueryWrapper<LayoutCell>().eq(LayoutCell::getCellVersionId,versionId));

        List<LayoutCell> root=new ArrayList<>();
        Map<String,LayoutCell> map=new HashMap<>();
        for (LayoutCell layoutCell:layoutCells){
            if(layoutCell.getCellParent().longValue()==0){
                root.add(layoutCell);
            }
            map.put(layoutCell.getCellId().toString(),layoutCell);
            if(layoutCell.getCellType().equals("3")){
                if(null==layoutCell.getCellDict()){
                    layoutCell.setDict(new FormDict());
                }else{
                    FormDict dict=dictService.selectDictByParent(layoutCell.getCellDict(),recordItmMap);
                    layoutCell.setDict(dict);
                }
            }
        }
        //遍历Map缕清父子关系
        Iterator<String> keys = map.keySet().iterator();
        while(keys.hasNext()){
            String key = keys.next();
            LayoutCell layoutCell1 = map.get(key);
            if(layoutCell1.getCellParent().longValue()!=0){
                LayoutCell parentLayoutCell=map.get(layoutCell1.getCellParent().toString());
                parentLayoutCell.getChildrens().add(layoutCell1);
            }
        }
        root.forEach(cell->{
            cell.setChildrens(cell.getChildrens().stream().sorted(Comparator.comparing(LayoutCell::getCellId)).collect(Collectors.toList()));
        });
        return root;
    }

    @Override
    public int saveCell(JSONArray jsonNArray, Long versionId) {
        this.lambdaUpdate().eq(LayoutCell::getCellVersionId,versionId).remove();

        LayoutVersion layoutVersion=layoutVersionMapper.selectById(versionId);
        Long layout=layoutVersion.getLayoutId();
        for(int i=0;i<jsonNArray.size();i++){
            LayoutCell layoutCell=new LayoutCell(layout,"1","row",null,0L,versionId);
            this.save(layoutCell);   //保存行
            Long rowId=layoutCell.getCellId();
            JSONArray columnsJSONArr=jsonNArray.getJSONArray(i);
            for(int j=0;j<columnsJSONArr.size();j++){
                JSONObject json=columnsJSONArr.getJSONObject(j);
                LayoutCell columnLayoutCell=new LayoutCell(layout,"2",json.getString("style"),null,rowId,versionId);
                this.save(columnLayoutCell);  //保存列
                Long columnId=columnLayoutCell.getCellId();
                JSONArray dictJSONArr=json.getJSONArray("dicts");
                for(int k=0;k<dictJSONArr.size();k++){
                    LayoutCell dictLayoutCell=new LayoutCell(layout,"3","",dictJSONArr.getLong(k),columnId,versionId);
                    this.save(dictLayoutCell);  //字典
                }
            }
        }
        return 0;
    }
}
